import json
from django.http import JsonResponse

from book.models import BookInfo
from rest_framework.response import Response

from .serializer import BookSerializer
from django.shortcuts import render
from rest_framework.generics import GenericAPIView
# Create your views here.
from django.views import View
"""
GenericAPIView 继承APIView,增加了对于列表视图和详情视图可能用到的通用支持方法。
通常使用时，可搭配一个或多个Mixin扩展类。
"""


class Books(GenericAPIView):
    # 指定当前类视图使用的查询集数据
    queryset = books = BookInfo.objects.all()
    # 指定当前类视图使用的序列化器
    serializer_class = BookSerializer

    def get(self,request):
        # 1、查询所有图书对象
        # books = BookInfo.objects.all()
        books = self.get_queryset()  # 获取查询集中的所有数据
        # ser= BookSerializer(books, many=True)
        ser = self.get_serializer(books, many=True)  # 使用指定序列化器

        return Response(ser.data)
        # return JsonResponse(ser.data, safe=False)

    def post(self, request):
        # 1、获取前端数据
        # data = request.body.decode()
        # data_dict = json.loads(data)
        data = request.data
        # 2、验证数据
        # ser= BookSerializer(data=data)
        ser = self.get_serializer(data=data)
        ser.is_valid()  # 验证方法

        # 3、保存数据
        # print(ser.data)
        ser.save()
        # 4、返回结果
        # return JsonResponse(ser.data)
        return Response(ser.data)


class Book(GenericAPIView):
    def get(self, request):
        book = BookInfo.objects.get(id=1)
        ser = BookSerializer(book)

        return Response(ser.data)


class BookDRFView(GenericAPIView):
    """
        获取单一和更新和删除
    """
    queryset = BookInfo.objects.all()
    serializer_class = BookSerializer

    def put(self, request, pk):
        # 1、获取前端数据
        # data = request.body.decode()
        # data_dict = json.loads(data)
        data = request.data
        print('come in')
        # 2、验证数据
        try:
            # book = BookInfo.objects.get(id=pk)
            book = self.get_object()
        except:
            return JsonResponse({'error': '错误信息'}, status=400)
        ser=BookSerializer(book,data=data)
        ser.is_valid()
        # 3、更新数据
        ser.save()
        # 4、返回结果
        # return JsonResponse(ser.errors)
        return Response(ser.data)

    def delete(self, request, pk):
        # 1、查询数据对象
        try:
            book = BookInfo.objects.get(id=pk)

        except:
            # return JsonResponse({'error': '错误信息'}, status=400)
            return Response({'error': '错误信息'}, status=400)

        book.is_delete=True
        book.save()
        return Response({})
